﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Reflection;

namespace PreCommitHook
{
    public class XmlAppender
    {
        public void Write(string projFileName, string assemblyName, string fileName)
        {
            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            XDocument xDoc = XDocument.Load(path + @"\SolutionAssemblies\SolutionAssemblies.xml");

            //if the assembly exists but the file doesn't exists append it. if we call this method the file doesn't exists 
            //because it is already checked for existance in GetFileAssembly, PreCommitValidator class
            var assmeblyExists = (from el in xDoc.Root.Elements()
                                  where el.Name.LocalName.Equals("assembly") && ((string)el.Attribute("name") == assemblyName) && ((string)el.Attribute("projFileName") == projFileName)
                                  select el.Element("contentFiles")
                                  );

            if (assmeblyExists.ToList().Count > 0)
            {
                XElement assemblyElement = assmeblyExists.ToList()[0] as XElement;
                assemblyElement.Add(new XElement("file", fileName));
            }
            //if neither the file nor the assembly exists create them
            else
            {
                xDoc.Element("assemblies").Add(new XElement("assembly",
                                                        new XAttribute("name", assemblyName),
                                                        new XAttribute("projFileName", projFileName),
                                                        new XElement("contentFiles",
                                                                    new XElement("file", fileName))
                    ));
            }
            xDoc.Save(path + @"\SolutionAssemblies\SolutionAssemblies.xml");
        }
    }
    public static class SolutionAssembliesWriter 
    {
       private static XmlAppender _writer = new XmlAppender();
       private static object _lock = new object();
       public static void Write(string projectFileName, string assemblyName, string fileName)
       {
           lock (_lock)
           {
               _writer.Write(projectFileName, assemblyName, fileName);
           }
       }
    }

}
